package com.manage.service.impl;

import com.manage.dao.IRoleDao;
import com.manage.dao.IUserDao;
import com.manage.domain.Role;
import com.manage.domain.UserInfo;
import com.manage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;
    @Autowired
    private IRoleDao roleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("User not found");
        }
        List<Role> roles = userInfo.getRoles();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (roles != null) {
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
            }
        }
        boolean enabled = userInfo.getStatus() != null && userInfo.getStatus() == 1;
        return new User(userInfo.getUsername(), userInfo.getPassword(), enabled, true, true, true, authorities);
    }

    @Override
    public UserInfo findByUsernameAndPassword(String username, String password) {
        return userDao.findByUsernameAndPassword(username, password);
    }
}


